package com.shine.app.ui;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TableRow;
import android.widget.TextView;

import com.shine.app.AppManager;
import com.shine.app.BaseActivity;
import com.shine.app.R;
import com.shine.app.bean.UserBean;
import com.shine.app.bean.UserInfoBean;
import com.shine.app.bean.request.UpdatePasswordBean;
import com.shine.app.bean.responses.ValidateResponse;
import com.shine.app.commons.StringUtils;
import com.shine.app.commons.UIHelper;
import com.shine.app.inject.InjectView;
import com.shine.app.inject.Injector;

public class ViewMyAccountPasswordActivity extends BaseActivity implements
		OnClickListener {

	@InjectView(R.id.head_back)
	private ImageView gobackImageView;
	@InjectView(R.id.head_name)
	private TextView nameTextView;
	@InjectView(R.id.current)
	private EditText currentEditText;
	@InjectView(R.id.news)
	private EditText newEditText;
	@InjectView(R.id.confirm)
	private EditText confirmEditText;

	@InjectView(R.id.currentr_error)
	private ImageView currentImageView;
	@InjectView(R.id.new_error)
	private ImageView newImageView;
	@InjectView(R.id.confirm_error)
	private ImageView confirmImageView;
	@InjectView(R.id.change)
	private Button changeButton;
	@InjectView(R.id.progressBar)
	private ProgressBar progressBar;
	@InjectView(R.id.currentTableRow)
	private TableRow currenTableRow;
	@InjectView(R.id.newTableRow)
	private TableRow newTableRow;
	@InjectView(R.id.confirmTableRow)
	private TableRow confirmTableRow;
	private UserInfoBean user;

	Handler passWordHandler = new Handler() {
		public void handleMessage(Message message) {
			if (message.what == 1) {
				ValidateResponse response = (ValidateResponse) message.obj;
				Boolean flag = response.isData();
				if (flag) {
					newEditText.getText().clear();
					currentEditText.getText().clear();
					confirmEditText.getText().clear();
					UIHelper.toastDialog(ViewMyAccountPasswordActivity.this,
							R.string.changesuccess, R.string.msg_yes);
				} else {
					UIHelper.toastDialog(ViewMyAccountPasswordActivity.this,
							R.string.changefail, R.string.msg_yes);
				}
			} else if (message.what == 0) {
				UIHelper.toastDialog(ViewMyAccountPasswordActivity.this,
						R.string.changefail, R.string.msg_yes);
			} else if (message.what == -1) {
				Exception exception = (Exception) message.obj;
				UIHelper.toastDialogs(ViewMyAccountPasswordActivity.this,
						exception.getMessage(), R.string.msg_yes);
			}
			resetViewStatus(true);
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.viewaccount_password);
		Injector.get(this).inject();
		initPassword();
	}

	private void initPassword() {
		user = appContext.getLoginInfo();
		progressBar.setVisibility(View.GONE);
		nameTextView.setText(R.string.account_password);
		changeButton.setOnClickListener(this);
		gobackImageView.setOnClickListener(this);
		currentEditText.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
				validate(true, currentImageView, currenTableRow);
			}
		});
		newEditText.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
				if ((s.toString()).equals(confirmEditText.getText().toString()
						.trim())) {
					validate(true, confirmImageView, confirmTableRow);
					validate(true, newImageView, newTableRow);
				}
			}
		});
		confirmEditText.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
				if ((s.toString()).equals(newEditText.getText().toString()
						.trim())) {
					validate(true, confirmImageView, confirmTableRow);
					validate(true, newImageView, newTableRow);
				}
			}
		});
	}

	private void validate(boolean flag, ImageView imageView, TableRow tableRow) {
		if (flag) {
			imageView.setVisibility(View.GONE);
			imageView.setTag(true);
			tableRow.setVisibility(View.GONE);
		} else {
			imageView.setVisibility(View.VISIBLE);
			imageView.setTag(false);
			tableRow.setVisibility(View.VISIBLE);
		}
	}

	private boolean validationPassword(String currentPassword,
			String newsPassword, String confirmPassword) {
		if (StringUtils.isEmpty(currentPassword)
				|| !(currentPassword.equals(user.getPassword()))) {
			validate(false, currentImageView, currenTableRow);
		} else {
			validate(true, currentImageView, currenTableRow);
		}
		if (StringUtils.isEmpty(newsPassword)) {
			validate(false, newImageView, newTableRow);
		} else {
			validate(true, newImageView, newTableRow);
		}
		if (StringUtils.isEmpty(newsPassword)
				|| StringUtils.isEmpty(confirmPassword)
				|| !(confirmPassword.equals(newsPassword))) {
			validate(false, confirmImageView, confirmTableRow);
			validate(false, newImageView, newTableRow);
		} else {
			validate(true, confirmImageView, confirmTableRow);
			validate(true, newImageView, newTableRow);
		}
		if (((Boolean) currentImageView.getTag())
				&& ((Boolean) newImageView.getTag())
				&& ((Boolean) confirmImageView.getTag())) {
			return true;
		} else {
			return false;
		}
	}

	private void updatePassword(final UpdatePasswordBean bean) {
		resetViewStatus(false);
		new Thread() {
			public void run() {
				Message message = new Message();
				try {
					ValidateResponse response = appContext.changePassword(bean);
					if (response != null) {
						if (response.isHasError()) {
							message.what = 0;
							message.obj = response;
						} else {
							message.what = 1;
							message.obj = response;
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
					message.what = -1;
					message.obj = e;
				}
				passWordHandler.sendMessage(message);
			}
		}.start();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {

		case R.id.head_back:
			AppManager.getAppManager().finishActivity();
			overridePendingTransition(R.anim.anim, R.anim.slide_out_down);
			break;

		case R.id.change:
			changeButton.startAnimation(buttonAnimations);
			inputMethodManager.hideSoftInputFromWindow(v.getWindowToken(), 0);
			String currentPassword = getEditTextValues(currentEditText);
			String newPassword = getEditTextValues(newEditText);
			String confirm = getEditTextValues(confirmEditText);
			if (!validationPassword(currentPassword, newPassword, confirm)) {
				return;
			}
			if (appContext.isLogin()) {
				UserBean user = appContext.getLoginInfo().getUser();
				if (!StringUtils.isEmpty(user.getUserId())) {
					UpdatePasswordBean passwordBean = new UpdatePasswordBean(
							currentPassword, newPassword, user.getUserId());
					updatePassword(passwordBean);
				}
			} else {
				UIHelper.showLogin(ViewMyAccountPasswordActivity.this);
			}
			break;

		default:
			break;
		}
	}

	private void resetViewStatus(boolean flag) {
		if (flag) {
			progressBar.setVisibility(View.GONE);
		} else {
			progressBar.setVisibility(View.VISIBLE);
		}
		changeButton.setClickable(flag);
		gobackImageView.setClickable(flag);
		currentEditText.setEnabled(flag);
		newEditText.setEnabled(flag);
		confirmEditText.setEnabled(flag);
	}
}
